package com.vgemv.jsutilitysdk.secretbutton;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;


public class GajSecretButton extends View {

    static private int smi_secretEventTapCount = 11;
    private int mi_tapCount = 0;
    //连续两次点击的最大间隔ms数
    private int mi_continousTapInterval = 1000;
    private IGajSecretButtonCallback mCallback;
    private long ml_firstTapTime;
    private long ml_checkTime;
    private TimerTask mTimerTask;
    private Timer mTimer;

    public GajSecretButton(Context context) {
        super(context);
    }

    public GajSecretButton(Context context, AttributeSet attributeSet) {
        super(context,attributeSet);
    }

    public GajSecretButton(Context context,  AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context,attrs,defStyleAttr,defStyleRes);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mi_tapCount ++;
        if(mi_tapCount == 1) {
            ml_firstTapTime = System.currentTimeMillis();
            ml_checkTime = ml_firstTapTime+mi_continousTapInterval;
            mTimer = new Timer();
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    onTimer();
                }
            };
            mTimer.schedule(mTimerTask,0,500);
        }
        else {
            //增加点击次数,延长判定时间

            ml_checkTime = System.currentTimeMillis()+ mi_continousTapInterval;

        }

        return super.onTouchEvent(event);
    }

    public void judgeSecretActionResult() {
        if(mi_tapCount == smi_secretEventTapCount) {
            //点击次数达到设定值.
            mCallback.onSecretEvent();
        }
        //释放资源,重置点击次数
        mTimer.cancel();
        mTimerTask.cancel();
        mTimer = null;
        mTimerTask = null;
        mi_tapCount = 0;
    }

    public void onTimer() {
        long ml_now = System.currentTimeMillis();
//        //GajLogManager.log(.log("onTimer,now is %d,checkTime is %d, diff is %d",ml_now,ml_checkTime,ml_checkTime-ml_now);
        if(ml_now < ml_checkTime) {
            //还没到判定时间,不操作.
        }
        else {
            //进入判定
            judgeSecretActionResult();

        }
    }

    public void setCallback(IGajSecretButtonCallback callback) {
        this.mCallback = callback;
    }
}
